package com.keyboardr.gamerater;

import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.View;
import android.widget.ListView;

public class PlayersFragment extends ListFragment {
	long lastId = -1;
	int lastGroupSize = -1;

	@Override
	public void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		if (bundle != null) {
			lastId = bundle.getLong("selectedPlayer", -1);
			lastGroupSize = bundle.getInt("lastGroupSize", -1);
		}
	}

	@Override
	public void onStart() {
		super.onStart();
		setListAdapter(new PlayerAdapter((RaterActivity) getActivity()));
		getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);

		if (lastId >= 0
				&& lastGroupSize == ((RaterActivity) getActivity())
						.getSelectedGroup().getPlayers().size()) {
			Player selected = ((RaterActivity) getActivity())
					.getSelectedGroup().getPlayers().get((int) lastId);
			if (selected != null) {
				int index = ((RaterActivity) getActivity()).getSortedList()
						.indexOf(selected);
				((ListFragment) getFragmentManager().findFragmentByTag(
						"players")).getListView().setItemChecked(index, true);
			}
		}
	}

	@Override
	public void onSaveInstanceState(Bundle bundle) {
		int position = getListView().getCheckedItemPosition();
		long id = getListView().getItemIdAtPosition(position);
		bundle.putLong("selectedPlayer", id);
		bundle.putInt("lastGroupSize", ((RaterActivity) getActivity())
				.getSelectedGroup().getPlayers().size());
	}

	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		if (RaterActivity.isHolo) {
			((GamesFragment) getFragmentManager().findFragmentByTag("games"))
					.setFilter((Player) getListAdapter().getItem(position));
		}
	}

	public void clearSelection() {
		getListView().setItemChecked(-1, true);
	}
}
